#!/bin/bash

while read line;
do
    sample=`echo $line | cut -d' '  -f1`
    dad=`echo $line | cut -d' '  -f2`
    mom=`echo $line | cut -d' '  -f3`

    echo $sample
    # full siblings
    if [[ $dad != 0 && $mom != 0 ]];
    then
	awk -v dad=$dad -v mom=$mom -v sample=$sample '$1!=sample && $2==dad && $3==mom {print sample, $1}' "Soapv2.fam" >> sibs_genotyped.txt
    fi
    # half sibs through dad
    if [[ $dad != 0 ]];
    then
	awk -v dad=$dad -v sample=$sample '$1!=sample && $2==dad {print sample, $1}' "Soapv2.fam" >> half_sibs_genotyped.txt
    fi
    # half sibs through mom
    if [[ $mom != 0 ]];
    then
	awk -v mom=$mom -v sample=$sample '$1!=sample && $3==mom {print sample, $1}' "Soapv2.fam" >> half_sibs_genotyped.txt
    fi
done < "Soapv2.fam"

# remove duplicates (above process adds relationship A-B as well as B-A)

# cp sibs_genotyped.txt temp.txt
echo "" > temp.txt
while read line;
do
  sample1=`echo $line | cut -d' ' -f1`  
  sample2=`echo $line | cut -d' ' -f2`  

  if grep -q "$sample2 $sample1" temp.txt
  then
      echo $line
  else
      echo $line >> temp.txt
  fi    
done < "sibs_genotyped.txt"
mv temp.txt sibs_genotyped.txt

echo "" > temp.txt
while read line;
do
  sample1=`echo $line | cut -d' ' -f1`  
  sample2=`echo $line | cut -d' ' -f2`  

  if grep -q "$sample2 $sample1" temp.txt
  then
      echo $line
  else
      echo $line >> temp.txt
  fi    
done < "half_sibs_genotyped.txt"
mv temp.txt half_sibs_genotyped.txt
